/*
 * FlatShader.cpp
 *
 *  Created on: 27-06-2013
 *      Author: Jarek
 */

#include "FlatShader.h"
#include <EMatrix4x4.h>
#include <ETexture.h>

FlatShader::FlatShader(char* VSPath, char* FSPath)
{
	createShader(VSPath, FSPath);
	createProgram();

	uniforms.projectionMatrix 	= glGetUniformLocation(programHandler, "projMatrix");
	uniforms.texture	 		= glGetUniformLocation(programHandler, "texture");

	attributes.position			= glGetAttribLocation(programHandler, "position");
	attributes.texCoords		= glGetAttribLocation(programHandler, "texCoords");

	if (uniforms.projectionMatrix < 0)
		LOGE("Flat shader: couldn't find uniform \"projMatrix\".");
	if (uniforms.texture < 0)
		LOGE("Flat shader: couldn't find uniform \"texture\".");
	if (attributes.position	< 0)
		LOGE("Flat shader: couldn't find attribute \"position\".");
	if (attributes.texCoords < 0)
		LOGE("Flat shader: couldn't find attribute \"texCoords\".");
}

FlatShader::~FlatShader()
{
	// TODO Auto-generated destructor stub
}

void FlatShader::useAttributes(bool isAttributes)
{
	if(isAttributes)
	{
		glEnableVertexAttribArray(attributes.position);
		glEnableVertexAttribArray(attributes.texCoords);
	}
	else
	{
		glDisableVertexAttribArray(attributes.position);
		glDisableVertexAttribArray(attributes.texCoords);
	}
}

void FlatShader::draw(Matrix4x4<float> projectionMatrix, GLuint indicesHandle, GLuint verticesHandle, GLuint texcoordsHandle, const Texture& texture, uint verticesCount)
{
	this->useProgram();
	this->useAttributes();

	this->setUniformMatrix4x4f(uniforms.projectionMatrix, &projectionMatrix.at(0, 0));

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesHandle);

	glBindBuffer(GL_ARRAY_BUFFER, verticesHandle);
	glEnableVertexAttribArray(attributes.position);
	glVertexAttribPointer(attributes.position, 3, GL_FLOAT, GL_FALSE, 0, 0);

	glBindBuffer(GL_ARRAY_BUFFER, texcoordsHandle);
	glEnableVertexAttribArray(attributes.texCoords);
	glVertexAttribPointer(attributes.texCoords, 2, GL_FLOAT, GL_FALSE, 0, 0);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texture.handle);
	glUniform1i(uniforms.texture, 0);

	glDrawElements(GL_TRIANGLES, verticesCount, GL_UNSIGNED_INT, 0);
}

